package cn.krund.lyc.hotlerobot.wifimanage;

import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Point;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.TextWatcher;
import android.util.ArrayMap;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Map;

import cn.krund.lyc.hotlerobot.R;
import cn.krund.lyc.hotlerobot.activity.ui.WifiFunctionActivity;

/**
 * @包名: cn.krund.lyc.hotlerobot.wifimanage
 * @作者: 刘育成
 * @时间: 2018/3/27  11:33
 * @org: 克路德人工智能
 * @描述: TODO
 * @fileName: WifiConnDialog
 */
public class WifiConnDialog extends Dialog {
    private Context context;
    private WifiManager mWifiManager;
    private ScanResult scanResult;
    private String wifiName;
    private String securityLevel;//安全性
    private int level; //信号强度
    private Map<String, WifiUserInfo> userWifiMap;
    private TextView tv_wifi_name; //wifi名
    private TextView tv_signal_strength; //信号强度
    private TextView tv_security_level;//安全性
    private EditText edt_password; //输入密码
    private CheckBox cbx_show_pass;//显示密码
    private TextView tv_btn_cancel; //取消
    private TextView tv_btn_connect;//连接
    WifiAdmin wifiAdmin;
    boolean isConn;
    private String type = "";
    private WifiUserInfo wui;
    private boolean isAutoConn = false;

    public WifiConnDialog(Context context, int theme) {
        super(context, theme);
    }


    private SharedPreferences spf;

    /**
     * @param context
     * @param theme
     * @param wifiName     wifi名
     * @param singlStren   信号强度
     * @param securityLevl 安全性
     */
    public WifiConnDialog(Context context, int theme, String wifiName,
                          int singlStren, String securityLevl) {
        super(context, theme);
        this.context = context;
        this.wifiName = wifiName;
        this.level = singlStren;
        this.securityLevel = securityLevl;
        spf = context.getSharedPreferences("Token", Context.MODE_PRIVATE);
    }


    public WifiConnDialog(Context context, int theme, ScanResult scanResult) {
        this(context, theme, scanResult.SSID, scanResult.level,
                scanResult.capabilities);
        this.scanResult = scanResult;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wifi_conn_dialog);
        setCanceledOnTouchOutside(false); //);//设置点击Dialog外部任意区域关闭
        initView();
        setListener();
    }


    private void initView() {
        tv_wifi_name = (TextView) findViewById(R.id.tv_wifi_name);
        tv_signal_strength = (TextView) findViewById(R.id.tv_signal_strength);
        tv_security_level = (TextView) findViewById(R.id.tv_security_level);
        tv_btn_cancel = (TextView) findViewById(R.id.tv_btn_cancel);
        tv_btn_connect = (TextView) findViewById(R.id.tv_btn_connect);
        edt_password = (EditText) findViewById(R.id.edt_password);
        cbx_show_pass = (CheckBox) findViewById(R.id.cbx_show_pass);

        tv_wifi_name.setText(wifiName);

        tv_signal_strength.setText(WifiAdmin.singlLevToStr(level));
        tv_security_level.setText(securityLevel);
        //取得wifimanager对象
        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

    }


    private void setListener() {

        edt_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() < 8) {
                    tv_btn_connect.setEnabled(false);
                    tv_btn_connect.setTextColor(Color.GRAY);
                } else {
                    tv_btn_connect.setTextColor(Color.BLACK);
                    tv_btn_connect.setEnabled(true);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //显示密码
        cbx_show_pass.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // 文本正常显示
                    edt_password
                            .setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    Editable etable = edt_password.getText();
                    Selection.setSelection(etable, etable.length());

                } else {
                    // 文本以密码形式显示
                    edt_password.setInputType(InputType.TYPE_CLASS_TEXT
                            | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    // 下面两行代码实现: 输入框光标一直在输入文本后面
                    Editable etable = edt_password.getText();
                    Selection.setSelection(etable, etable.length());
                }
            }
        });

        //取消
        tv_btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WifiConnDialog.this.dismiss();
            }
        });

        //连接
        tv_btn_connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WifiConnDialog.this.dismiss();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (scanResult.capabilities.toUpperCase().contains("WPA")) {
                            type = "WPA";
                        } else if (scanResult.capabilities.toUpperCase().contains("WEP")) {
                            type = "WEP";
                        } else {
                            type = "NOPASS";
                        }
                        // 连接网络
                        wifiAdmin = WifiFunctionActivity.m_wifiAdmin;
                        isAutoConn = true;
                        isConn = wifiAdmin.connect(scanResult.SSID, edt_password.getText().toString().trim(), type);
                        wifiAdmin.setOnNetworkChangeListener(new OnNetworkChangeListener() {
                            @Override
                            public void onNetWorkDisConnect() {
                            }

                            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                            @Override
                            public void onNetWorkConnect() {
                                if (isAutoConn) {
                                    showShortToast("连接成功");
                                    WifiFunctionActivity.m_wifiAdapter.notifyDataSetChanged();
                                    userWifiMap = new ArrayMap<String, WifiUserInfo>();
                                    InsertWifiUserInfoToMap(scanResult.SSID, edt_password.getText().toString().trim(), type);
                                    boolean save = PutInfoToMap.putMap(context, "wifiInfo", userWifiMap);
                                    isAutoConn = false;
                                }
                            }
                        });
                    }
                }).start();
            }
        });
    }

    private void InsertWifiUserInfoToMap(String name, String password, String type) {
        wui = new WifiUserInfo();
        if (!name.equals("")) {
            wui.setName(name);
            wui.setPassword(password);
            wui.setType(type);
        }
        userWifiMap.put(name, wui);
    }

    @Override
    public void show() {
        WindowManager wm = (WindowManager) getContext().getSystemService(
                Context.WINDOW_SERVICE);
        Point size = new Point();
        wm.getDefaultDisplay().getSize(size);
        super.show();
        getWindow().setLayout((int) (size.x * 9 / 10),
                ViewGroup.LayoutParams.WRAP_CONTENT);

    }

    private void showShortToast(String text) {
        Toast.makeText(context, text, Toast.LENGTH_LONG).show();
    }
}



